<template>
  <view class="page">
    <!-- 页面头部 -->
    <view class="header">
      <view class="stats">
        <view class="stat-item">
          <view class="stat-label">待处理</view>
          <view class="stat-value">{{ pendingCount }}</view>
        </view>
        <view class="stat-item">
          <view class="stat-label">进行中</view>
          <view class="stat-value">{{ cookingCount }}</view>
        </view>
        <view class="stat-item">
          <view class="stat-label">已完成</view>
          <view class="stat-value">{{ completedCount }}</view>
        </view>
      </view>
    </view>

    <!-- 状态筛选标签 -->
    <view class="filter-tabs">
      <view 
        v-for="tab in tabs" 
        :key="tab.value"
        class="tab-item"
        :class="{ active: activeTab === tab.value }"
        @click="activeTab = tab.value"
      >
        {{ tab.label }}
      </view>
    </view>

    <!-- 订单列表 -->
    <view class="orders-container">
      <!-- 空状态 -->
      <view v-if="filteredOrders.length === 0" class="empty-state">
        <view class="empty-icon">📋</view>
        <view class="empty-text">暂无订单</view>
        <view class="empty-desc">{{ getEmptyText() }}</view>
      </view>

      <!-- 订单卡片 -->
      <view v-else class="orders-list">
        <view 
          v-for="order in filteredOrders" 
          :key="order._id"
          class="order-card"
          :class="{ active: order.status === activeTab }"
        >
          <!-- 订单卡片头部 -->
          <view class="card-header">
            <view class="order-info">
              <view class="order-no">{{ order.order_no }}</view>
              <view class="order-time">{{ formatTime(order.create_date) }}</view>
            </view>
            <view class="status-badge" :class="getStatusClass(order.status)">
              {{ getStatusText(order.status) }}
            </view>
          </view>

          <!-- 菜品列表 -->
          <view class="dishes-section">
            <view 
              v-for="(dish, index) in order.dishes" 
              :key="index"
              class="dish-item"
            >
              <view class="dish-name">{{ dish.name }}</view>
              <view class="dish-qty">× {{ dish.count }}</view>
            </view>
          </view>

          <!-- 备注 -->
          <view v-if="order.remarks" class="remarks-section">
            <view class="remarks-label">备注：</view>
            <view class="remarks-text">{{ order.remarks }}</view>
          </view>

          <!-- 用户评价显示（已完成订单） -->
          <view v-if="order.rating" class="rating-section">
            <!-- 评价标题栏（可点击展开/折叠） -->
            <view class="rating-header-clickable" @click="toggleRatingExpanded(order._id)">
              <view class="rating-title-left">
                <view class="rating-score">
                  <text class="score-number">{{ order.rating.overall_score }}</text>
                  <text class="score-star">★</text>
                </view>
                <view class="rating-date">{{ formatTime(order.rating.rated_date) }}</view>
              </view>
              <view class="rating-toggle-icon" :class="{ expanded: expandedRatings[order._id] }">
                ▼
              </view>
            </view>
            
            <!-- 评价详细内容（展开时显示） -->
            <view v-if="expandedRatings[order._id]" class="rating-content">
              <!-- 总体评价 -->
              <view v-if="order.rating.overall_comment" class="overall-comment">
                {{ order.rating.overall_comment }}
              </view>
              
              <!-- 菜品评价 -->
              <view v-if="order.rating.dishes && order.rating.dishes.length > 0" class="dishes-rating">
                <view 
                  v-for="(dishRating, index) in order.rating.dishes" 
                  :key="index"
                  class="dish-rating-item"
                >
                  <view class="dish-rating-header">
                    <view class="dish-name">{{ dishRating.dish_name }}</view>
                    <view class="dish-score">
                      <text class="score-number">{{ dishRating.score }}</text>
                      <text class="score-star">★</text>
                    </view>
                  </view>
                  <view v-if="dishRating.comment" class="dish-comment">
                    {{ dishRating.comment }}
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 订单操作按钮 -->
          <view class="card-actions">
            <button 
              v-if="order.status === 0" 
              class="btn-accept"
              @click="acceptOrder(order)"
            >
              接单
            </button>
            <button 
              v-if="order.status === 1" 
              class="btn-start"
              @click="startCooking(order)"
            >
              开始制作
            </button>
            <button 
              v-if="order.status === 2" 
              class="btn-complete"
              @click="completeOrder(order)"
            >
              完成
            </button>
            <button 
              v-if="order.status !== 3" 
              class="btn-detail"
              @click="viewDetail(order)"
            >
              详情
            </button>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="hasMore" class="load-more">
          <button class="load-btn" @click="loadMore" :disabled="loading">
            {{ loading ? '加载中...' : '加载更多' }}
          </button>
        </view>
      </view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { onShow, onHide } from '@dcloudio/uni-app'
import orderWatch from '@/common/order-watch.js'
import audio from '@/common/audio.js'

const orders = ref([])
const activeTab = ref(0)  // 0=待处理, 1=已接单, 2=制作中, 3=已完成
const page = ref(1)
const pageSize = 20
const loading = ref(false)
const hasMore = ref(true)
const total = ref(0)
const expandedRatings = ref({})  // 跟踪哪些订单的评价是展开的

const tabs = [
  { label: '待处理', value: 0 },
  { label: '已接单', value: 1 },
  { label: '制作中', value: 2 },
  { label: '已完成', value: 3 }
]

// 切换评价展开状态
const toggleRatingExpanded = (orderId) => {
  expandedRatings.value[orderId] = !expandedRatings.value[orderId]
}

// 计算统计数据
const pendingCount = computed(() => 
  orders.value.filter(o => o.status === 0).length
)
const cookingCount = computed(() => 
  orders.value.filter(o => [1, 2].includes(o.status)).length
)
const completedCount = computed(() => 
  orders.value.filter(o => o.status === 3).length
)

// 过滤订单
const filteredOrders = computed(() => {
  return orders.value.filter(o => o.status === activeTab.value)
})

// 启动订单监听
const startOrderWatch = () => {
  orderWatch.startOrderWatch({
    role: 'chef',
    onOrderCreated: (newOrder) => {
      console.log('收到新订单:', newOrder)
      playNewOrderSound()
      if (!orders.value.find(o => o._id === newOrder._id)) {
        orders.value.unshift(newOrder)
      }
      uni.showToast({
        title: '新订单！',
        icon: 'success',
        duration: 2000
      })
    },
    onOrderUpdated: (updatedOrder) => {
      console.log('订单已更新:', updatedOrder)
      const index = orders.value.findIndex(o => o._id === updatedOrder._id)
      if (index !== -1) {
        orders.value[index] = updatedOrder
      }
      uni.showToast({
        title: `订单${getStatusText(updatedOrder.status)}`,
        icon: 'success',
        duration: 2000
      })
    }
  })
}

// 播放新订单提示音
const playNewOrderSound = () => {
  audio.playNewOrderAlert()
}

// 获取空状态文字
function getEmptyText() {
  const texts = {
    0: '没有待处理订单',
    1: '没有已接单的订单',
    2: '没有制作中的订单',
    3: '没有已完成的订单'
  }
  return texts[activeTab.value] || '暂无订单'
}

// 格式化时间
function formatTime(timestamp) {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取状态样式
function getStatusClass(status) {
  const statusMap = {
    0: 'status-pending',
    1: 'status-accepted',
    2: 'status-cooking',
    3: 'status-completed'
  }
  return statusMap[status] || 'status-pending'
}

// 获取状态文字
function getStatusText(status) {
  const statusMap = {
    0: '待处理',
    1: '已接单',
    2: '制作中',
    3: '已完成'
  }
  return statusMap[status] || '未知状态'
}

// 加载订单列表
async function loadOrders(loadMore = false) {
  if (loading.value) return
  
  loading.value = true
  try {
    const res = await uniCloud.callFunction({
      name: 'food-order',
      data: {
        action: 'get-orders',
        data: {
          page: page.value,
          pageSize: pageSize
        }
      }
    })

    if (res.result && res.result.code === 200) {
      const { list = [], totalPages = 0 } = res.result.data || {}
      
      if (loadMore) {
        orders.value = [...orders.value, ...list]
      } else {
        orders.value = list.sort((a, b) => {
          // 优先显示待处理和进行中的订单
          const order1 = [0, 1, 2].includes(a.status) ? 0 : 1
          const order2 = [0, 1, 2].includes(b.status) ? 0 : 1
          if (order1 !== order2) return order1 - order2
          // 同类订单按创建时间倒序
          return new Date(b.create_date) - new Date(a.create_date)
        })
      }
      
      hasMore.value = page.value < totalPages
      total.value = res.result.data?.count || 0
    } else {
      uni.showToast({
        title: res.result?.message || '加载失败',
        icon: 'none'
      })
    }
  } catch (err) {
    uni.showToast({
      title: '加载订单失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 接单
async function acceptOrder(order) {
  uni.showModal({
    title: '确认接单',
    content: `确定要接单 ${order.order_no} 吗？`,
    async success(res) {
      if (res.confirm) {
        try {
          const updateRes = await uniCloud.callFunction({
            name: 'food-order',
            data: {
              action: 'update-order-status',
              data: {
                orderId: order._id,
                status: 1
              }
            }
          })

          if (updateRes.result && updateRes.result.code === 200) {
            uni.showToast({ title: '已接单', icon: 'success' })
            order.status = 1
            order.status_time = updateRes.result.data.statusTime
          } else {
            uni.showToast({
              title: updateRes.result?.message || '操作失败',
              icon: 'none'
            })
          }
        } catch (err) {
          uni.showToast({ title: '操作失败', icon: 'none' })
        }
      }
    }
  })
}

// 开始制作
async function startCooking(order) {
  uni.showModal({
    title: '确认开始制作',
    content: `开始制作订单 ${order.order_no}？`,
    async success(res) {
      if (res.confirm) {
        try {
          const updateRes = await uniCloud.callFunction({
            name: 'food-order',
            data: {
              action: 'update-order-status',
              data: {
                orderId: order._id,
                status: 2
              }
            }
          })

          if (updateRes.result && updateRes.result.code === 200) {
            uni.showToast({ title: '开始制作', icon: 'success' })
            order.status = 2
            order.status_time = updateRes.result.data.statusTime
          } else {
            uni.showToast({
              title: updateRes.result?.message || '操作失败',
              icon: 'none'
            })
          }
        } catch (err) {
          uni.showToast({ title: '操作失败', icon: 'none' })
        }
      }
    }
  })
}

// 完成订单
async function completeOrder(order) {
  uni.showModal({
    title: '确认完成',
    content: `订单 ${order.order_no} 已完成？`,
    async success(res) {
      if (res.confirm) {
        try {
          const updateRes = await uniCloud.callFunction({
            name: 'food-order',
            data: {
              action: 'update-order-status',
              data: {
                orderId: order._id,
                status: 3
              }
            }
          })

          if (updateRes.result && updateRes.result.code === 200) {
            uni.showToast({ title: '已完成', icon: 'success' })
            order.status = 3
            order.status_time = updateRes.result.data.statusTime
          } else {
            uni.showToast({
              title: updateRes.result?.message || '操作失败',
              icon: 'none'
            })
          }
        } catch (err) {
          uni.showToast({ title: '操作失败', icon: 'none' })
        }
      }
    }
  })
}

// 查看详情
function viewDetail(order) {
  uni.navigateTo({
    url: `/pages/order-detail/order-detail?id=${order._id}`
  })
}

// 加载更多
function loadMore() {
  if (!hasMore.value || loading.value) return
  page.value += 1
  loadOrders(true)
}

// 检查登录状态
function checkLogin() {
  try {
    const userInfo = uniCloud.getCurrentUserInfo()
    if (!userInfo || !userInfo.uid) {
      // 未登录，跳转到登录页面
      uni.navigateTo({
        url: '/uni_modules/uni-id-pages/pages/login/login-withpwd'
      })
      return false
    }
    return true
  } catch (err) {
    // 获取用户信息失败，跳转到登录页面
    uni.navigateTo({
      url: '/uni_modules/uni-id-pages/pages/login/login-withpwd'
    })
    return false
  }
}

onMounted(() => {
  if (checkLogin()) {
    loadOrders()
    startOrderWatch() // 启动订单监听
  }
})

onShow(() => {
  if (checkLogin()) {
    page.value = 1
    loadOrders()
    // 重新启动订单监听
    if (!orderWatch.isOrderWatchActive()) {
      startOrderWatch()
    }
  }
})

onUnmounted(() => {
  orderWatch.stopOrderWatch() // 卸载订单监听
})
</script>

<style lang="scss" scoped>
$primary-color: #10b981;
$warning-color: #f59e0b;
$danger-color: #ef4444;
$success-color: #10b981;
$pending-color: #fbbf24;

.page {
  min-height: 100vh;
  background: #f8fafc;
}

.header {
  background: #fff;
  padding: 24rpx;
  border-bottom: 1rpx solid #e5e7eb;
  
  .stats {
    display: flex;
    gap: 20rpx;
    
    .stat-item {
      flex: 1;
      background: #f3f4f6;
      padding: 16rpx;
      border-radius: 12rpx;
      text-align: center;
      
      .stat-label {
        font-size: 24rpx;
        color: #6b7280;
        margin-bottom: 8rpx;
      }
      
      .stat-value {
        font-size: 40rpx;
        font-weight: 700;
        color: $primary-color;
      }
    }
  }
}

.filter-tabs {
  display: flex;
  gap: 12rpx;
  padding: 16rpx 24rpx;
  background: #fff;
  border-bottom: 1rpx solid #e5e7eb;
  overflow-x: auto;
  
  .tab-item {
    padding: 10rpx 20rpx;
    border-radius: 20rpx;
    background: #f3f4f6;
    color: #6b7280;
    font-size: 26rpx;
    white-space: nowrap;
    transition: all 0.3s;
    
    &.active {
      background: $primary-color;
      color: #fff;
    }
  }
}

.orders-container {
  padding: 16rpx;
  
  .empty-state {
    text-align: center;
    padding: 120rpx 32rpx;
    
    .empty-icon {
      font-size: 80rpx;
      margin-bottom: 20rpx;
    }
    
    .empty-text {
      font-size: 32rpx;
      font-weight: 600;
      color: #0f172a;
      margin-bottom: 12rpx;
    }
    
    .empty-desc {
      font-size: 26rpx;
      color: #6b7280;
    }
  }
  
  .orders-list {
		display: flex;
		flex-direction: column;
    gap: 16rpx;
  }
  
  .order-card {
    background: #fff;
    border-radius: 12rpx;
    padding: 20rpx;
    box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.06);
    border-left: 4rpx solid #e5e7eb;
    transition: all 0.3s;
    
    &.active {
      border-left-color: $primary-color;
      box-shadow: 0 4rpx 12rpx rgba(16, 185, 129, 0.1);
    }
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 16rpx;
      
      .order-info {
        flex: 1;
        
        .order-no {
          font-size: 28rpx;
          font-weight: 600;
          color: #0f172a;
          margin-bottom: 6rpx;
        }
        
        .order-time {
          font-size: 24rpx;
          color: #6b7280;
        }
      }
      
      .status-badge {
        padding: 6rpx 12rpx;
        border-radius: 8rpx;
        font-size: 22rpx;
        font-weight: 600;
        white-space: nowrap;
        
        &.status-pending {
          background: #fef3c7;
          color: #92400e;
        }
        
        &.status-accepted {
          background: #dbeafe;
          color: #1e40af;
        }
        
        &.status-cooking {
          background: #fed7aa;
          color: #d97706;
        }
        
        &.status-completed {
          background: #d1fae5;
          color: #065f46;
        }
      }
    }
    
    .dishes-section {
      background: #f9fafb;
      padding: 12rpx;
      border-radius: 8rpx;
      margin-bottom: 16rpx;
      
      .dish-item {
        display: flex;
        justify-content: space-between;
        padding: 8rpx 0;
        font-size: 26rpx;
        color: #111827;
        border-bottom: 1rpx solid #e5e7eb;
        
        &:last-child {
          border-bottom: none;
        }
        
        .dish-name {
          flex: 1;
        }
        
        .dish-qty {
          color: $primary-color;
          font-weight: 600;
        }
      }
    }
    
    .remarks-section {
      background: #f0fdf4;
      padding: 12rpx;
      border-radius: 8rpx;
      margin-bottom: 16rpx;
      font-size: 26rpx;
      color: #065f46;
      
      .remarks-label {
        font-weight: 600;
        margin-bottom: 4rpx;
      }
      
      .remarks-text {
        color: #059669;
      }
    }
    
    .rating-section {
      background: #f0fdf4;
      padding: 12rpx;
      border-radius: 8rpx;
      margin-bottom: 16rpx;
      font-size: 26rpx;
      color: #065f46;
      
      .rating-header-clickable {
        display: flex;
        justify-content: space-between;
        align-items: center;
        cursor: pointer;
        padding-bottom: 8rpx;
        border-bottom: 1rpx dashed #e5e7eb;
        margin-bottom: 8rpx;
      }

      .rating-title-left {
        display: flex;
        align-items: baseline;
        gap: 12rpx;
      }

      .rating-toggle-icon {
        font-size: 24rpx;
        color: #6b7280;
        transition: transform 0.3s ease;

        &.expanded {
          transform: rotate(180deg);
        }
      }

      .rating-content {
        padding-top: 8rpx;
        border-top: 1rpx dashed #e5e7eb;
        margin-top: 8rpx;
      }
      
      .rating-score {
        display: flex;
        align-items: baseline;
        font-size: 32rpx;
        font-weight: 700;
        color: $success-color;
        
        .score-number {
          font-size: 36rpx;
        }
        
        .score-star {
          font-size: 28rpx;
        }
      }
      
      .rating-date {
        font-size: 24rpx;
        color: #9ca3af;
        margin-left: 12rpx;
      }
      
      .overall-comment {
        margin-bottom: 12rpx;
        font-style: italic;
        color: #4b5563;
      }
      
      .dishes-rating {
        .dish-rating-item {
          margin-bottom: 12rpx;
          
          .dish-rating-header {
            display: flex;
            justify-content: space-between;
            align-items: baseline;
            margin-bottom: 4rpx;
            
            .dish-name {
              font-weight: 600;
              color: #111827;
            }
            
            .dish-score {
              display: flex;
              align-items: baseline;
              font-size: 26rpx;
              font-weight: 600;
              color: $success-color;
              
              .score-number {
                font-size: 28rpx;
              }
              
              .score-star {
                font-size: 24rpx;
              }
            }
          }
          
          .dish-comment {
            font-size: 24rpx;
            color: #4b5563;
          }
        }
      }
    }
    
    .card-actions {
		display: flex;
      gap: 12rpx;
      justify-content: flex-end;
      
      button {
        padding: 10rpx 16rpx;
        border: none;
        border-radius: 8rpx;
        font-size: 24rpx;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
        
        &:active {
          opacity: 0.9;
        }
      }
      
      .btn-accept {
        background: $primary-color;
        color: #fff;
      }
      
      .btn-start {
        background: $warning-color;
        color: #fff;
      }
      
      .btn-complete {
        background: $success-color;
        color: #fff;
      }
      
      .btn-detail {
        background: #e5e7eb;
        color: #374151;
      }
    }
  }
  
  .load-more {
    text-align: center;
    padding: 24rpx 0;
    
    .load-btn {
      background: #f3f4f6;
      color: #6b7280;
      border: none;
      border-radius: 8rpx;
      padding: 16rpx 32rpx;
      font-size: 26rpx;
      cursor: pointer;
      
      &:disabled {
        opacity: 0.6;
      }
    }
  }
	}
</style>
